import server from '@/api/pages'
import { PageAttr, SiteAttr, ComponentTypes } from '@/store/default-styles'
import {guid} from '@/plugins/utils'
import { COMPONENT_TYPES, PAGE_TYPE_, ALIGN_TYPE, ALIGN_HORIZONTAL_TYPE, SITE_DEFAULT_BG, MEDIAS, PAGE_TYPE } from '@/common/const'
import { MOBILE_WID_HEI } from '@/common/const-dif'
import { EVENT_HOVER_TYPES, ROTATE3D_LIST, INTERACTION_DATA, EVENT_ATTR } from '@/common/events'
import { copySiteData } from '@/common/site-data'
import { dealVoteList} from "@/store/modules/wb-components"
import { initSiteData, saveDealSiteData, initComponent, deleteComponentControl, addComponentData, copyGroupComponentControls } from "@/store/components-utils"
import { searchComponentDataById } from "@/store/index-utils"
import { ADD_COMP_ATTR } from "@/store/default-styles-dom"
import { initComponentMapInPage } from "@/store/index-utils"
import { isJSON } from '@/plugins/utils'
import { isHasOwnProperty } from '@/plugins/utils'
import { EventBus } from '@/store/index'
import { getPxOVwByValue } from '@/store/utils'

// initial state
const initState = {
  componentMap: {},
  pages: [],
  currentPage: null,
  position: {left:0, top:0},
  currentComponentData: null,
  fileUploadData: null,//上传文件需要数据
  //站点属性
  id: '-1',
  styles: null,
  attrs: _.cloneDeep(SiteAttr.attrs),
  activityInfo: {
    isHave: false
  },
  tabNames: {
    text: 'tab-0',
    img: 'tab-0',
    page: 'tab-0',
  },
  siteStatus: {
    scale: 1,
    loading: false,
    isShift: false,
    isEdit: false,//输入文本双击可编辑状态，delete按钮return
    shiftComponents:[],
    isHighComponentConfiguration: false,
    isCopySite: false,
    isTab: false,
    zIndex: 0,
    isUploadFile: false,
    uploadImgSize: 1,
  },
  recordComponentDatas: [],
  rightMenu: {
    isVisible: false,
    left: 0,
    top: '-1000px',
  },
  componentFrontAttr: {},//前端交互组件可见性
}
const state = _.cloneDeep(initState)

// getters
const getters = {
  getH5Pages: (state) => {
    return  _.filter(state.pages, function(o) { return o && o.type == PAGE_TYPE_.page; });
  },
  getPopPages: (state) => {
    return  _.filter(state.pages, function(o) { return o.type == PAGE_TYPE_.pop; });
  },
  isSite: (state) => {
    if(state.currentPage && (state.currentPage.type == PAGE_TYPE_.pop ||  state.attrs.isCurrentPage)){
      return false;
    }else{
      return true;
    }
  },
  isWbEvent: (state) => {
    let isWb = false;
    if(state.currentComponentData){
      _.forEach(state.currentComponentData.events, (event) => {
        if(event.controlId && event.controlId.length > 0){
          isWb = true;
        }
      })
    }
    return isWb
  },
  
}
// actions
const actions = {
  setRightMenuStatus({commit}, params){
    commit('setRightMenuStatus', params)
  },
  singleAlignComponents({commit}, type){
    commit('singleAlignComponents', type)
  },
  alignComponents({commit}, type){
    commit('alignComponents', type)
  },
  isGroupCurrentComponent({commit}, isGroup){
    // commit('updateShiftComponents', false)
    //坐标系转换
    let shiftComponents = state.siteStatus.shiftComponents;
    if(isGroup){
      if(shiftComponents.length < 2){
        return
      }
      let comps = _.cloneDeep(shiftComponents);
      let len = comps.length;
      let comp;
      let minxs = [];
      let maxxs = [];
      let minys = [];
      let maxys = [];
      let minx = 0;
      let maxx = 0;
      let miny = 0;
      let maxy = 0;
      let i = 0;
      for( i = 0; i < len; i++){
        comp = comps[i];
        minxs.push(comp.conAttr.left);
        maxxs.push(comp.conAttr.left + comp.conAttr.width);
        minys.push(comp.conAttr.top);
        maxys.push(comp.conAttr.top + comp.conAttr.height);
      }
      minx = _.min(minxs);
      maxx = _.max(maxxs);
      miny = _.min(minys);
      maxy = _.max(maxys);
      for(i = 0; i < len; i++){
        comp = comps[i];
        comp.conAttr.left -= minx;
        comp.conAttr.top -= miny;
        comp.conStyles.left = comp.conAttr.left + "px";
        comp.conStyles.top = comp.conAttr.top + "px";
      }
      let newGroupComponent = _.cloneDeep(getComponentDataByCid(COMPONENT_TYPES.group_component));
      _.merge(newGroupComponent, ADD_COMP_ATTR);
      newGroupComponent.conAttr.width = maxx - minx;
      newGroupComponent.conAttr.height = maxy - miny;

      newGroupComponent.conAttr.left = minx;
      newGroupComponent.conAttr.top = miny;

      newGroupComponent.conStyles.width = maxx - minx + "px";
      newGroupComponent.conStyles.height = maxy - miny + "px";

      newGroupComponent.conStyles.left = minx + "px";
      newGroupComponent.conStyles.top = miny + "px";
      newGroupComponent.id = guid();

      newGroupComponent.components =  _.concat(newGroupComponent.components, comps);
      newGroupComponent.conAttr.zIndex = parseInt(state.siteStatus.zIndex);
      newGroupComponent.conStyles.zIndex = newGroupComponent.conAttr.zIndex
      newGroupComponent.active = true;

      commit('removeShiftComponents')
      commit('addComponent', newGroupComponent)
      commit('setActiveComponentId', newGroupComponent.id)
      state.siteStatus.isShift = false
    }else{
      if(state.currentComponentData && state.currentComponentData.components && state.currentComponentData.components.length > 0){
        let comps = state.currentComponentData.components
        let componentData = state.currentComponentData
        commit('removeCurrentComponent');
        commit('setActiveComponentId');
        commit('wbComponents/deleteControl', componentData.id, {root:true});
        commit('wbComponents/setActiveWbData', null, {root:true});
        let comp;
        for(let i = 0, len = comps.length; i < len; i++){
          comp = comps[i];
          comp.conAttr.left += componentData.conAttr.left;
          comp.conAttr.top += componentData.conAttr.top;

          comp.conStyles.left = comp.conAttr.left + "px";
          comp.conStyles.top = comp.conAttr.top + "px";

          commit('addComponent', comp);
          commit('setActiveComponentId', comp.id);
          if(_.size(comp.events) > 0){
            for(let key in comp.events){
              let event = comp.events[key]
              if(event.controlId && event.controlId.length > 0){
                commit('wbComponents/setActiveWbData', comp, {root:true})
                break
              }
            }
          }
        }
      }
    }
  },
  updateSiteScale({commit}, params){
    commit('updateSiteScale', params)
  },
  updateKeyDownShift({commit}, params){
    commit('updateKeyDownShift', params)
  },
  updateShiftComponents({commit}, params){
    commit('updateShiftComponents', params)
  },
  createSite:({commit, state}, params_) => {
    let params = {id:"", tag: params_.type};
    let $router = params_.$router;
    server.createSite(params, (data) => {
      commit('wbComponents/setControls', {}, {root:true});
      commit('setPageDatas', data);
      commit('setActivePage', state.pages[0]);
      let id = data.id;
      $router.push({ path: `/h5edit/${id}`});
      window.setTimeout(function(){
        let controls = {};
        let data = saveDealSiteData(controls, _.cloneDeep(state));
        server.savePageDatas(data, function(){
          commit('savePageDatas');
        });
      }, 50);
    });
  },
  createCopySite({commit}, params_){
    let params = {id:"", tag: params_.type};
    let $router = params_.$router;
    server.createSite(params, (data) => {
      let id = data.id;
      let siteData = {}
      _.merge(siteData, params_.data)
      siteData.id = id
      commit('wbComponents/setControls', siteData.controls, {root:true});
      commit('setPageDatas', siteData);
      commit('setActivePage', siteData.pages[0]);
      $router.push({ path: `/h5edit/${id}`});
      window.setTimeout(function(){
        let controls = siteData.controls;
        let data_ = saveDealSiteData(controls, siteData);
        server.savePageDatas(data_, function(){
          commit('savePageDatas');
        });
      }, 50);
    });
  },
  savePageDatas: (store, cb) => {
    const { commit, rootState } = store;
    let controls = _.cloneDeep(rootState.wbComponents.controls);
    let data = saveDealSiteData(controls, _.cloneDeep(state));
    rootState.user.siteDatas[data.id] = _.cloneDeep(data);
    if(state.siteStatus.isCopySite && isJSON(copySiteData)){
      data = _.cloneDeep(copySiteData)
      data.id = state.id
    }
    server.savePageDatas(data, function(){
      commit('savePageDatas');
      if(cb) cb();
    });
  },
  setLocalData: ({commit}) => {
    let data = JSON.parse(localStorage.siteData);
    commit('setPageDatas', data);
    commit('setActivePage', state.pages[0]);
    commit('wbComponents/setControls', data.controls, {root:true});
  },
  getPageDatas: (store, params_) => {
    const { commit } = store;
    if(!state.fileUploadData){
      server.getFileUploadData((data) => {
        commit("setFileUploadData", data);
      });
    }
    server.getPageDatas({id:params_.id}, (data) => {
      data.id = params_.id;
      commit('setPageDatas', data);
      commit('setActivePage', state.pages[0]);
      let controls = data.controls;
      delete controls[""]
      delete data.controls;
      commit('wbComponents/setControls', controls, {root:true});
      commit('wbComponents/setActiveWbData', state.currentPage, {root:true});
    });
  },
  addPage: ({commit}, params) => {
    let page = _.cloneDeep(PageAttr);
    page.type = params.type;
    page.isActive = false;
    page.id = guid();
    commit('addPage', page)
    commit('setActiveComponentId');
    commit('setActivePage', page);
  },
  deletePage: ({commit}, params) => {
    let pageIndex = getPageIndexById(params.id);
    if(pageIndex == -1){
      return;
    }
    let page = getPageById(params.id);
    // commit('setActiveComponentId');
    commit('deletePage', pageIndex);
    commit('wbComponents/deleteControl', params.id, {root:true});
    if(state.pages.length > 0){
      let page = getPageById(state.pages[0].id);
      commit('setActivePage', page);
    }

    page.components.forEach((componentData) => {
      commit('wbComponents/deleteControl', componentData.id, {root:true});
      if(componentData.components && componentData.components.length > 0){
        deleteComponentControl(commit, componentData)
      }
    });
  },
  copyPage: ({commit}, params) => {
    let page = _.cloneDeep(getPageById(params.id));
    page.id = guid();
    commit('wbComponents/addEventControlToControls', {copyId: params.id, compId: page.id}, {root:true});
    let compId
    let copyId
    _.forEach(page.components, (componentData) => {
      copyId = componentData.id
      compId = guid()
      componentData.id = compId
      commit('wbComponents/addEventControlToControls', {copyId, compId}, {root:true});
      if(componentData.components && componentData.components.length > 0){
        copyGroupComponentControls(commit, componentData)
      }
    })
    let pageIndex = getPageIndexById(params.id);
    commit('copyPage', { page, pageIndex });
    commit('setActiveComponentId');
    commit('setActivePage', page);
  },
  setActivePage: ({commit}, {id}) => {
    let page
    if(id != -1){
      page = getPageById(id);
    }
    commit('setActiveComponentId');
    commit('setActivePage', page);
    commit('wbComponents/setActiveWbData', state.currentPage, {root:true});
  },
  addPageEvent: ({ commit }, {event, controlData}) => {
    commit('addPageEvent', event);
    const controlId = event.controlId;
    const currentPage = state.currentPage;
    if(controlId && controlId.length > 0){
      commit('wbComponents/setActiveWbData', currentPage, {root:true});
      commit('wbComponents/addEventControlToCurrentControls', {controlId, controlData, id: currentPage.id}, {root:true});
    }
    commit('recordComponentAttr');
  },
  updatePageEvent: ({commit}, data) => {
    commit('updatePageEvent', data);
    commit('recordComponentAttr');
  },
  deletePageEvent: ({commit}, data) => {
    commit('deletePageEvent', data);
    commit('recordComponentAttr');
  },
  updatePageStyles: ({commit}, styles) => commit('updatePageStyles', styles),
  updatePageAttrs: ({commit}, attrs) => commit('updatePageAttrs', attrs),
  updatePageAttrsById: ({commit}, attrs) => commit('updatePageAttrsById', attrs),
  addComponent: ({commit}, params) => {
    let hei = 0;
    if(state.currentComponentData){
      hei = state.currentComponentData.conAttr.height
    }
    let position = { left: state.position.left, top: state.position.top + hei };
    let componentData = initComponent(params, position, state.siteStatus);

    let top = state.currentPage.attrs.height - componentData.conAttr.height;
    if(position.top > top){
      componentData.conAttr.top = top;
    }else if(position.top > MOBILE_WID_HEI.height){
      componentData.conAttr.top = MOBILE_WID_HEI.height - componentData.conAttr.height;
    }
    let left = state.currentPage.attrs.width - componentData.conAttr.width;
    if(position.left > left){
      componentData.conAttr.left = left;
    }
    if(componentData.conAttr.left < 0){
      componentData.conAttr.left = 0;
    }else if(componentData.conAttr.left > MOBILE_WID_HEI.width){
      componentData.conAttr.left = MOBILE_WID_HEI.width - componentData.conAttr.width
    }
    addComponentData(componentData, commit);

    // 更新 底部菜单 isTab，为 true 则 禁用滑动翻页
    if(COMPONENT_TYPES.wb_menu == componentData.cid) {
      commit('setIfTab', true);
    }
  },
  addComponentItem: ({commit}, params) => {
    commit('addComponentItem', params);
    commit('recordComponentAttr');
  },
  deleteComponentItem: ({commit}, params) => {
    commit('deleteComponentItem', params);
    commit('recordComponentAttr');
  },
  updateComponentItem: ({commit}, params) => {
    commit('updateComponentItem', params);
    commit('recordComponentAttr');
  },
  changeWH: ({commit}, rect) => {
    commit('changeWH', rect);
    commit('recordComponentAttr');
  },
  recordMousePosition: ({commit}, position) => {
    commit('recordMousePosition', position);
    // commit('recordComponentAttr');
  },
  recordComponentAttr: ({commit}) => commit('recordComponentAttr'),
  cancelComponentAttr: ({commit}) => commit('cancelComponentAttr'),
  updateInnerComponentWHOrPosition: ({commit}, params) => {
    commit('updateInnerComponentWHOrPosition', params);
    commit('recordComponentAttr');
  },
  setActiveComponentId: (store, componentData) => {
    let { commit } = store;
    // let { rootState, commit, state } = store;
    commit('setActiveComponentId', componentData ? componentData.id : null);

    commit('wbComponents/setActiveWbData', componentData ? componentData : state.currentPage, {root:true});

    commit('hiddenImgCropPop', {}, {root:true});

    commit('changeSelectEventPlane', {isActive: false, type: ''}, {root:true});
    commit('changeSelectAnimatePlane', {isActive: false}, {root:true});
  },
  setDragComponentZIndex: ({commit}) => {
    commit('setDragComponentZIndex');
    commit('recordComponentAttr');
  },
  adjustComponentZIndex: ({commit}, zIndex) => {
    commit('adjustComponentZIndex', zIndex);
    commit('recordComponentAttr');
  },
  copyCurrentComponent: ({ commit }) => {
    let componentData = _.cloneDeep(state.currentComponentData);
    //对于打组的组件进行处理
    if(componentData.components && componentData.components.length > 0){
      copyGroupComponentControls(commit, componentData)
    }

    let compId
    let copyId
    copyId = componentData.id
    compId = guid()
    componentData.id = compId;
    commit('wbComponents/addEventControlToControls', {copyId, compId}, {root:true});

    componentData.conAttr.top += 40;
    componentData.conStyles.top = getPxOVwByValue(componentData.conAttr.top);
    addComponentData(componentData, commit)
  },
  removeCurrentComponent: ({commit}) => {
    if(state.siteStatus.isEdit || !state.currentComponentData){
      return;
    }
    // 更新 底部菜单 isTab，为 true 则 禁用滑动翻页
    if(COMPONENT_TYPES.wb_menu == state.currentComponentData.cid) {
      commit('setIfTab', false);
    }
    let componentData = state.currentComponentData
    commit('removeCurrentComponent');
    commit('setActiveComponentId');
    commit('wbComponents/deleteControl', componentData.id, {root:true});
    if(componentData.components && componentData.components.length > 0){
      deleteComponentControl(commit, componentData)
    }
    commit('wbComponents/setActiveWbData', null, {root:true});
  },
  updateComponentStyles: ({commit}, styles) => {
    commit('updateComponentStyles', styles);
    commit('recordComponentAttr');
  },
  cropImg: ({commit, rootState}, params) => {
    server.cropImg(params, (url) => {
      if(!state.currentComponentData){
        let styles = {backgroundImage:'url(' + url + ')'};
        let attrs =  {bgUrl: url};
        if(getters.isSite()){
          commit('updateSiteStyles', styles);
          commit('updateSiteAttrs', attrs);
        }else{
          commit('updatePageStyles', styles);
          commit('updatePageAttrs', attrs);
        }
      }else{
        let comAttr = rootState.mediaPop.comAttr;
        let picAttr = rootState.mediaPop.picAttr;
        let index = rootState.mediaPop.index;
        if(index >= 0){
          let data_ = {item:{}, index};
          data_.item[picAttr] = url;
          if(this.mediaPop.event && this.mediaPop.event.controlId){
            data_.controlId = this.mediaPop.event.controlId
            this.updateWbComponentItem(data_);
          }else{
            this.updateComponentItem(data_);
          }
        }else{
          let isHaveCom = comAttr && comAttr.length > 0;
          let params = {};

          if(isHaveCom){
            params[comAttr] = {};
            params[comAttr][picAttr] = url;
          }else{
            params[picAttr] = url;
          }
          if(picAttr == 'bgUrl'){
            if(isHaveCom){
              params[comAttr].styles = {backgroundImage:'url('+url+')'};
            }else{
              params.styles = {backgroundImage:'url('+url+')'};
            }
          }
          commit('updateCurrentComponentData', params);
        }
      }
    })
  },
  updateCurrentComponentData: ({commit}, data) => {
    commit('updateCurrentComponentData', data);
    commit('recordComponentAttr');
  },
  setIsEdit: ({commit}, data) => commit('setIsEdit', data),
  generateQrcode: ({commit}, params) => {
    server.generateQrcode(params, (data) => {
      commit('generateQrcode', data)
    })
  },
  addAnimate: ({commit}, params) => {
    commit('addAnimate', params)
  },
  deleteAnimate: ({commit}, params) => {
    commit('deleteAnimate', params)
  },
  updateCurrentAnimateItem: ({commit}, params) => commit('updateCurrentAnimateItem', params),
  updateAnimateIndex: ({commit}, params) => {
    commit('updateAnimateIndex', params)
  },
  playAnimateAll: ({commit}, params) => {
    commit('playAnimateAll', params)
  },
  updateAnimateByIndex: ({commit}, params) => {
    commit('updateAnimateByIndex', params)
  },
  addEvent: ({ commit, state }, {event, controlData}) => {
    commit('addEvent', event);
    let componentData = state.currentComponentData;
    let controlId = event.controlId
    if(controlId && controlId.length > 0){
      commit('wbComponents/setActiveWbData', componentData, {root:true});
      commit('wbComponents/addEventControlToCurrentControls', {controlId, controlData, id: componentData.id}, {root:true});
    }
    commit('recordComponentAttr');
    commit('dealVoteListCommit');
  },
  updateEvent: ({commit}, data) => {
    commit('updateEvent', data);
    commit('recordComponentAttr');
  },
  changeEventIndex: ({commit}, data) => {
    commit('changeEventIndex', data);
    commit('recordComponentAttr');
  },
  deleteEvent: ({commit}, event) => {
    commit('deleteEvent', event)
    if(event.controlId && event.controlId.length > 0){
      commit('wbComponents/deleteEventControlToControls', { event, id: state.currentComponentData.id }, {root:true});
    }
    commit('recordComponentAttr');
  },
  updateSettingShare: ({commit}, params) => {
    commit('updateSettingShare', params);
  },
  updateSettingMore: ({commit}, params) => {
    commit('updateSettingMore', params);
  },
  updateSiteAttrs: ({commit}, params) => {
    commit('updateSiteAttrs', params);
  },
  updateSiteEventAttrs: ({commit}, params) => {
    commit('updateSiteEventAttrs', params);
  },
  updateSiteStyles: ({commit}, params) => {
    commit('updateSiteStyles', params);
  },
  updateTab: ({commit}, params) => {
    commit('updateTab', params);
  },
  updateSettingBgm: ({commit}, params) => {
    commit('updateSettingBgm', params);
  },

  /* fileUploadData */
  getFileUploadData: ({commit}) => {  /* get fileUploadData */
    server.getFileUploadData((data) => {
      commit("setFileUploadData", data);
    });
  },
}

// mutations
const mutations = {
  dealVoteListCommit(){
    dealVoteList()
  },
  updateSiteStatus(state, data){
    _.merge(state.siteStatus, data)
    if(state.siteStatus.isHighComponentConfiguration){
      localStorage.isHighComponentConfiguration = true
    }
  },
  setRightMenuStatus(state, data){
    _.merge(state.rightMenu, data);
  },
  singleAlignComponents(state){
    const componentData = state.currentComponentData;
    if(componentData){
      let left = parseInt((MOBILE_WID_HEI.width - componentData.conAttr.width)/2);
      componentData.conAttr.left = left;
      componentData.conStyles.left = getPxOVwByValue(left);
    }
  },
  alignComponents(state, type){
    let minTop = 0;
    let maxTop = 0;
    let maxBottom = 0;
    let minLeft = 0;
    let maxLeft = 0;
    let maxRight = 0;
    // let minRight = 0;
    let maxHeight = 0;
    // let minHeight = 0;
    let maxWidth = 0;
    // let minWidth = 0;
    let distance = 0;
    let allHeight = 0;
    let allWidth = 0;

    let tops = [];
    let bottoms = [];
    let lefts = [];
    let rights = [];
    let heights = [];
    let widths = [];
    let shiftComponents = state.siteStatus.shiftComponents

    if(ALIGN_HORIZONTAL_TYPE.indexOf(type) != -1){
      shiftComponents = _.sortBy(shiftComponents, (componentData) => {
        return componentData.conAttr.left
      })
    }else{
      shiftComponents = _.sortBy(shiftComponents, (componentData) => {
        return componentData.conAttr.top
      })
    }

    let len = shiftComponents.length-1
    _.forEach(shiftComponents, (componentData, index) => {
      let conAttr = componentData.conAttr
      conAttr.top = parseInt(conAttr.top)
      tops.push(conAttr.top)
      bottoms.push(conAttr.top + conAttr.height)
      lefts.push(conAttr.left)
      rights.push(conAttr.left + conAttr.width)
      heights.push(conAttr.height)
      widths.push(conAttr.width)
      if(index != len){
        allHeight += conAttr.height
        allWidth += conAttr.width
      }
    })
    minTop = _.min(tops)
    maxTop = _.max(tops)
    maxBottom = _.max(bottoms)
    maxLeft = _.max(lefts)
    minLeft = _.min(lefts)
    maxRight = _.max(rights)
    // minRight = _.min(rights)
    maxHeight = _.max(heights)
    // minHeight = _.min(heights)
    maxWidth = _.max(widths)
    // minWidth = _.min(widths)

    if(ALIGN_HORIZONTAL_TYPE.indexOf(type) != -1){
      distance = parseInt((maxLeft - minLeft - allWidth)/len)
    }else{
      distance = parseInt((maxTop - minTop - allHeight)/len)
    }

    _.forEach(shiftComponents, (componentData, index) => {
      if(ALIGN_TYPE.top == type){
        componentData.conAttr.top = minTop
        componentData.conStyles.top = getPxOVwByValue(minTop)
      }else if(ALIGN_TYPE.bottom == type){
        componentData.conAttr.top = maxBottom - componentData.conAttr.height
        componentData.conStyles.top = getPxOVwByValue(componentData.conAttr.top)
      }else if(ALIGN_TYPE.left == type){
        componentData.conAttr.left = minLeft
        componentData.conStyles.left = getPxOVwByValue(minLeft)
      }else if(ALIGN_TYPE.right == type){
        componentData.conAttr.left = maxRight - componentData.conAttr.width
        componentData.conStyles.left = getPxOVwByValue(componentData.conAttr.left)
      }else if(ALIGN_TYPE.horizontalCenterAlign == type){
        componentData.conAttr.top = minTop + parseInt(maxHeight/2) - componentData.conAttr.height/2
        componentData.conStyles.top = getPxOVwByValue(componentData.conAttr.top)
      }else if(ALIGN_TYPE.horizontalCenterDistribute == type){
        if(index > 0){
          let comp = shiftComponents[index-1]
          componentData.conAttr.left = parseInt(comp.conAttr.left) + parseInt(comp.conAttr.width) + distance
          componentData.conStyles.left = getPxOVwByValue(componentData.conAttr.left)
        }
      }else if(ALIGN_TYPE.verticalCenterAlign == type){
        componentData.conAttr.left = minLeft + parseInt((maxWidth)/2) - componentData.conAttr.width/2
        componentData.conStyles.left = getPxOVwByValue(componentData.conAttr.left)
      }else if(ALIGN_TYPE.verticalCenterDistribute == type){
        if(index > 0){
          let comp = shiftComponents[index-1]
          componentData.conAttr.top = parseInt(comp.conAttr.top) + parseInt(comp.conAttr.height) + distance
          componentData.conStyles.top = getPxOVwByValue(componentData.conAttr.top)
        }
      }
    })
  },
  removeShiftComponents(state){
    _.pullAll(state.currentPage.components, state.siteStatus.shiftComponents);
    while(state.siteStatus.shiftComponents.length > 0){
      state.siteStatus.shiftComponents.pop();
    }
  },
  updateSiteScale(state, data){
    state.siteStatus.scale = data;
  },
  updateKeyDownShift(state, isShift){
    state.siteStatus.isShift = isShift;
  },
  updateShiftComponents(state, isShift){
    if(isShift && state.currentComponentData){
      if(state.siteStatus.shiftComponents.indexOf(state.currentComponentData) == -1){
        state.siteStatus.shiftComponents.push(state.currentComponentData)
      }
    }
  },
  createSite(state, data){
    _.merge(state, data);
  },
  setIsEdit(state, data){
    state.siteStatus.isEdit = data;
  },
  savePageDatas(state){
    state.siteStatus.loading = false;
  },
  setPageDatas (state, data) {
    state.pages = null;
    state.currentPage = null;
    state.currentComponentData = null;
    state.styles = null;
    state.id = -1;
    state.attrs = _.cloneDeep(SiteAttr.attrs);
    let isEditSite = true;
    let siteStatus = state.siteStatus;
    let componentFrontAttr = state.componentFrontAttr;
    let fileUploadData = state.fileUploadData;

    initComponentMapInPage(state.componentMap, data.pages);

    // _.merge(state.componentMap["4169fae7-52ad-47b6-a765-de714686620d"].events, state.componentMap["cf6dde53-308c-4b3d-8d83-0a9fa6e412f5"].events)

    let siteData = initSiteData(data, isEditSite, siteStatus, componentFrontAttr, fileUploadData)
    // let page = siteData.pages[8]
    // let comps = page.components
    // delete page.components
    // page.components = []
    // siteData.pages[9].components = _.cloneDeep(comps)
    _.merge(state, siteData);
  },
  setFileUploadData(state, data){
    data.key = data.key.split("$")[0];
    state.fileUploadData = _.merge({ site_id: state.id, type: MEDIAS.image.type }, data);
  },
  addPage(state, page){
    state.pages.push(page);
    state.currentPage = page;
  },
  deletePage(state, pageIndex){
    state.pages.splice(pageIndex, 1);
  },
  copyPage(state, {page, pageIndex}){
    for(let j = 0, len = page.components.length; j < len; j++){
      let componentData = page.components[j];
      if(!isHasOwnProperty(state.componentFrontAttr, componentData.id)){
        state.componentFrontAttr[componentData.id] = { isHidden: false, isLock: false }
        // Vue.set(state.componentFrontAttr, componentData.id, {isHidden: false, isLock: false})
      }
    }
    state.pages.splice(pageIndex, 0 , page);
  },
  movePageIndex(state, {type, pageIndex}){
    const pages = _.filter(state.pages, function(o) { return o.type == PAGE_TYPE_.page; })
    const pops = _.filter(state.pages, function(o) { return o.type == PAGE_TYPE_.pop; });
    //1 page
    if(type == PAGE_TYPE.single){
      const page = pages[pageIndex-1];
      _.pullAt(pages, pageIndex-1);
      pages.splice(pageIndex, 0, page);
    }else{
      const pop = pops[pageIndex-1];
      _.pullAt(pops, pageIndex-1);
      pops.splice(pageIndex, 0, pop);
    }
    state.pages = pages.concat(pops);
  },
  updatePageStyles(state, styles){
    _.merge(state.currentPage.styles, styles)
  },
  updatePageAttrs(state, attrs){
    _.merge(state.currentPage, attrs)
  },
  updatePageAttrsById(state, params){
    let page = getPageById(params.id);
    if(!page){
      return;
    }
    for(var attr in params.attrs){
      page.attrs[attr] = params.attrs[attr];
    }
  },
  setActivePage(state, page){
    if(state.currentPage){
      state.currentPage.isActive = false;
      _.forEach(state.currentPage.components, (componentData) => {
        componentData.active = false;
      });
    }
    if(!page){
      state.currentPage = null;
      return
    }
    _.forEach(state.pages, (page) => {
      page.isActive = false;
    });
    _.forEach(page.components, (componentData) => {
      componentData.active = false;
    });
    //记录坐标
    let top = 100;
    let left = 20;
    let zIndex = 0;
    if(page && page.components.length > 0){
      top = page.components[0].conAttr.top;
      left = page.components[0].conAttr.left;
      zIndex = page.components[0].conAttr.zIndex + 1;
    }
    state.position.top = top;
    state.position.left = left;
    state.siteStatus.zIndex = zIndex;

    state.currentPage = page;
    state.currentPage.isActive = true;
    // state.currentPage.components = [];
  },
  addPageEvent(state, event){
    let currentPage = state.currentPage;
    event.index = _.size(currentPage.events)
    if(event.controlId && (!isHasOwnProperty(currentPage, "eventAttr") || _.isArray(currentPage.eventAttr))){
      let eventAttr = _.cloneDeep(EVENT_ATTR[event.controlId || event.type].wbAttr);
      currentPage['eventAttr'] = eventAttr;
      // Vue.set(currentPage, 'eventAttr', eventAttr);
    }
    if(isHasOwnProperty(currentPage.events, event.type)){
      currentPage.events[event.type] = event
    }else{
      currentPage.events[event.type] = event
      // Vue.set(currentPage.events, event.type, event)
    }
  },
  updatePageEvent(state, data){
    _.merge(state.currentPage.events[data.type], data.event);
  },
  deletePageEvent(state, {type, controlId}){
    delete state.currentPage.events[type];

    if(controlId && controlId.length > 0){
      let comps = EVENT_ATTR[controlId].comps;
      _.forEach(comps, (componentParams, key) => {
        delete state.currentPage[key];
      })
    }
    //刷新页面渲染
    let cloneEvents = _.cloneDeep(state.currentPage.events);
    state.currentPage['events'] = cloneEvents;
    // Vue.set(state.currentPage, 'events', cloneEvents);
  },
  setComponentFrontAttr(state, {id, attr}){
    if(!isHasOwnProperty(state.componentFrontAttr, id)){
      state.componentFrontAttr[id] = { isHidden: false, isLock: false }
      // Vue.set(state.componentFrontAttr, id, {isHidden: false, isLock: false})
    }
    _.merge(state.componentFrontAttr[id], attr)
  },
  addComponent(state, componentData){
    state.currentPage.components.push(componentData);
    if(!isHasOwnProperty(state.componentFrontAttr, componentData.id)){
      state.componentFrontAttr[componentData.id] = { isHidden: false, isLock: false }
      // Vue.set(state.componentFrontAttr, componentData.id, {isHidden: false, isLock: false})
    }
  },
  addComponentItem(state, data){
    let componentData = state.currentComponentData;
    if(componentData.commonAttr.isShiftInArr){
      componentData.lists.unshift(data);
    }else{
      componentData.lists.push(data);
    }
    dealVoteList()
  },
  deleteComponentItem(state, data){
    let componentData = state.currentComponentData;
    componentData.lists.splice(data.index, 1);
    dealVoteList()
  },
  updateComponentItem(state, data){
    let lists = state.currentComponentData.lists;
    let item = lists[data.index];
    for(let key in data.item){
      item[key] = data.item[key]
      if(_.isArray(data.item[key])){
        _.merge(item[key], data.item[key])
      }
    }
    dealVoteList()
  },
  addComponentAttrItem(state, data){
    state.currentComponentData[data.comAttr].lists.push(data.item);
  },
  deleteComponentAttrItem(state, data){
    state.currentComponentData[data.comAttr].lists.splice(data.index, 1);
  },
  updateComponentAttrItem(state, data){
    let lists = state.currentComponentData[data.comAttr].lists;
    let item = lists[data.index];
    for(let key in data.item){
      item[key] = data.item[key];
    }
  },
  changeWH(state, rect){
    if(state.currentComponentData){
      state.currentComponentData.conAttr.width = parseInt(rect.width);
      state.currentComponentData.conAttr.height = parseInt(rect.height);
      state.currentComponentData.conStyles.width = parseInt(rect.width) + "px";
      state.currentComponentData.conStyles.height = parseInt(rect.height) + "px";
    }
  },
  recordMousePosition (state, position) {
    state.position.left = position.left;
    state.position.top = position.top;
    let componentData = state.currentComponentData;
    if(componentData){
      componentData.conStyles.left = parseInt(position.left) + "px";
      componentData.conStyles.top = parseInt(position.top) + "px";
      componentData.conAttr.left = parseInt(position.left);
      componentData.conAttr.top = parseInt(position.top);
      if(isHasOwnProperty(position, "realTop")){
        componentData.conAttr.realTop = parseInt(position.realTop);
      }
      if(isHasOwnProperty(position, "otherCompHeight")){
        componentData.conAttr.otherCompHeight = parseInt(position.otherCompHeight);
      }
    }
  },
  recordComponentAttr(state){
    if(!state.currentComponentData){
      while(state.recordComponentDatas.length > 0){
        state.recordComponentDatas.pop()
      }
      return
    }
    let recordComponentDatas = state.recordComponentDatas
    let oldComponentData =  recordComponentDatas[recordComponentDatas.length-1]
    if(!oldComponentData || !_.isEqual(oldComponentData, state.currentComponentData)){
      let componentData = _.cloneDeep(state.currentComponentData)

      recordComponentDatas.push(componentData)
      if(recordComponentDatas.length > 30){
        recordComponentDatas.shift()
      }
    }
  },
  cancelComponentAttr(state) {
    if(!state.currentComponentData){
      while(state.recordComponentDatas.length > 0){
        state.recordComponentDatas.pop()
      }
      return
    }
    let recordComponentDatas = state.recordComponentDatas
    if(recordComponentDatas.length > 0){
      let componentData = recordComponentDatas.pop()
      _.merge(state.currentComponentData, componentData)
    }
  },
  updateInnerComponentWHOrPosition(state, params){
    _.merge(state.currentComponentData, params);
  },
  deactiveCurrentComponent(){
    if(state.currentComponentData){
      state.currentComponentData.active = false
    }
  },
  setActiveComponentId (state, id) {
    let componentData_;
    if(!state.currentPage){
      return;
    }
    _.forEach(state.currentPage.components, (compData) => {
      if(!state.siteStatus.isShift){
        compData.active = false;
      }
    })
    componentData_ = searchComponentDataById(id, state.currentPage);
    if(componentData_){
      componentData_.active = true;
      if(state.siteStatus.isShift){
        if(state.siteStatus.shiftComponents.indexOf(componentData_) == -1){
          state.siteStatus.shiftComponents.push(componentData_)
        }
      }
      if(isHasOwnProperty(componentData_, 'tabName') && !state.tabNames[componentData_.tabName]){
        state.tabNames[componentData_.tabName] = 'tab-0'
      }
    }
    state.currentComponentData = componentData_

    if(!state.currentComponentData || !state.siteStatus.isShift){
      while(state.siteStatus.shiftComponents.length > 0){
        state.siteStatus.shiftComponents.pop();
      }
      while(state.recordComponentDatas.length > 0){
        state.recordComponentDatas.pop()
      }
    }else{
      let top = state.currentComponentData.conAttr.top;
      let left = state.currentComponentData.conAttr.left;
      state.position.top = top;
      state.position.left = left;
    }
  },
  clearShiftComponents(){
    while(state.siteStatus.shiftComponents.length > 0){
      state.siteStatus.shiftComponents.pop();
    }
  },
  setDragComponentZIndex(){
    _.forEach(state.currentPage.components, function(componentData){
      if(componentData.conAttr.zIndex < 100){
        componentData.conAttr.zIndex = 0;
      }
    });
    if(state.currentComponentData){
      const zIndex = state.currentPage.components.length
      state.currentComponentData.conAttr.zIndex = zIndex
      state.currentComponentData.conStyles.zIndex = zIndex
    }
  },
  adjustComponentZIndex(state, zIndex){
    if(state.currentComponentData){
      state.currentComponentData.conAttr.zIndex = _.parseInt(zIndex);
      state.currentComponentData.conStyles.zIndex = _.parseInt(zIndex);
      if(zIndex > 0) {
        state.siteStatus.zIndex = zIndex
      }
    }
  },
  removeCurrentComponent(state){
    let index = _.indexOf(state.currentPage.components, state.currentComponentData);
    if(index != -1){
      state.currentPage.components.splice(index, 1);
    }
  },
  removeComponentById(state, id){
    const componentData = searchComponentDataById(id, state.currentPage);
    let index = _.indexOf(state.currentPage.components, componentData);
    if(index != -1){
      state.currentPage.components.splice(index, 1);
    }
  },
  updateComponentStyles (state, styles) {
    for(var attr in styles){
      state.currentComponentData.styles[attr] = styles[attr];
    }
    EventBus.$emit('refreshCommonAttr');
  },
  addEvent(state, event){
    let componentData = state.currentComponentData;
    event.index = _.size(componentData.events)
    if(isHasOwnProperty(componentData.events, event.type)){
      componentData.events[event.type] = event;
    }else{
      componentData.events[event.type] = event;
    }
    if(event.controlId && event.controlId.length > 0){
      if(!isHasOwnProperty(componentData, 'eventAttr')){
        let eventAttr = _.cloneDeep(EVENT_ATTR[event.controlId].wbAttr);
        componentData.eventAttr = eventAttr;
      }
    }else if(event.type == EVENT_HOVER_TYPES.rotate3d.type){
      if(!isHasOwnProperty(componentData, 'lists')){
        componentData.lists = _.cloneDeep(ROTATE3D_LIST);
      }
    }else if(event.type == EVENT_HOVER_TYPES.interactionData.type){
      if(!isHasOwnProperty(componentData, 'interactionData')){
        componentData.interactionData = _.cloneDeep(INTERACTION_DATA);
      }
    }
  },
  updateEvent(state, data){
    _.merge(state.currentComponentData.events[data.type], data.event);
  },
  changeEventIndex(state, {eventIndex}){
    let events = state.currentComponentData.events;
    let tempArr = [];
    tempArr = _.sortBy(events, (event) => { return event.index; });

    _.forEach(tempArr, (event_, index) => {
      if(index == eventIndex){
        event_.index = index-1;
      }else if(index == eventIndex-1){
        event_.index = index+1;
      }
    })
  },
  deleteEvent(state, {type, controlId}){
    delete state.currentComponentData.events[type];

    if(type == EVENT_HOVER_TYPES.rotate3d.type){
      delete state.currentComponentData.lists
    }else if(type == EVENT_HOVER_TYPES.interactionData.type){
      delete state.currentComponentData.interactionData
    }

    //从新设置index
    let events = state.currentComponentData.events;
    let tempArr = [];
    tempArr = _.sortBy(events, (event) => { return event.index; });
    _.forEach(tempArr, (event, index) => {
      event.index = index;
    })

    if(controlId && controlId.length > 0 && EVENT_ATTR[controlId]){
      let comps = EVENT_ATTR[controlId].comps;
      _.forEach(comps, (componentParams, key) => {
        delete state.currentComponentData[key];
      })
    }
  },
  updateOammAttr(state, oamm){
    _.merge(state.currentComponentData.oamm, oamm);
  },
  updateCurrentComponentData(state, data) {
    if(data.dataKeys && !isHasOwnProperty(state.currentComponentData, 'dataKeys')){
      state.currentComponentData['dataKeys'] = data.dataKeys;
      // Vue.set(state.currentComponentData, 'dataKeys', data.dataKeys)
    }
    if(!isHasOwnProperty(state.componentFrontAttr, data.id)){
      state.componentFrontAttr[ data.id] = { isHidden: false, isLock: false }
      // Vue.set(state.componentFrontAttr, data.id, { isHidden: false, isLock: false })
    }
    _.merge(state.currentComponentData, data);

    EventBus.$emit('refreshCommonAttr');
  },
  replaceCurrentComponentData(state, data) {
    _.merge(state.currentComponentData, data);
    state.currentComponentData.commonAttr = data.commonAttr
    EventBus.$emit('refreshCommonAttr');
  },
  updateInteractionData(state, data) {
    _.merge(state.currentComponentData.interactionData, data.interactionData);
  },
  addInteractionItem(state, data){
    let interactionData = state.currentComponentData.interactionData;
    let { index, item } = data;
    if(interactionData.isDimension){
      if(index >= 0){
        interactionData.dimensionLists[index].push(item);
      }else{
        interactionData.dimensionLists.push(item);
      }
    }else{
      interactionData.lists.push(item);
    }
  },
  deleteInteractionItem(state, data){
    let interactionData = state.currentComponentData.interactionData;
    let { index, qIndex } = data;
    if(interactionData.isDimension){
      if(qIndex >= 0){
        interactionData.dimensionLists[index].splice(qIndex, 1);
      }else{
        interactionData.dimensionLists.splice(index, 1);
      }
    }else{
      interactionData.lists.splice(index, 1);
    }
  },
  updateCurrentComponentDataDataKeys(state, data) {
    if(!isHasOwnProperty(state.currentComponentData, 'dataKeys')){
      state.currentComponentData['dataKeys'] = data.dataKeys;
      // Vue.set(state.currentComponentData, 'dataKeys', data.dataKeys);
    }else{
      state.currentComponentData.dataKeys = data.dataKeys
    }
  },
  updateCurrentComponentDataFilters(state, data) {
    if(!isHasOwnProperty(state.currentComponentData, 'filters')){
      state.currentComponentData['filters'] = data.filters;
      // Vue.set(state.currentComponentData, 'filters', data.filters);
    }else{
      // _.forEach(data.filters, (value, key) => {
      //   if(!isHasOwnProperty(state.currentComponentData.filters, key)){
      //     Vue.set(state.currentComponentData.filters, key, value)
      //   }
      // })
      state.currentComponentData.filters = data.filters
    }
  },
  generateQrcode(state, data){
    state.currentComponentData.commonAttr.url = data ? data.img_src : "";
  },
  addAnimate(state, item){
    state.currentComponentData.animate.animates.push(item);
  },
  deleteAnimate(state, index){
    state.currentComponentData.animate.isPlayAll = false;
    state.currentComponentData.animate.animates.splice(index, 1);
  },
  updateCurrentAnimateItem(state, item){
    state.currentComponentData.animate.isPlayAll = false;
    let playAnimateIndex = state.currentComponentData.animate.playAnimateIndex;
    _.merge(state.currentComponentData.animate.animates[playAnimateIndex], item);
  },
  updateAnimateIndex(state, index){
    state.currentComponentData.animate.isPlayAll = false;
    state.currentComponentData.animate.playAnimateIndex = index;
  },
  playAnimateAll(state, isPlayAll){
    state.currentComponentData.animate.isPlayAll = isPlayAll;
    let items = state.currentComponentData.animate.animates;
    for(let key in items){
      items[key].isPlaying = isPlayAll;
    }
  },
  updateAnimateByIndex(state, {index, item, triggerType}){
    if(!state.currentComponentData){
      return;
    }
    state.currentComponentData.animate.isPlayAll = false;
    _.merge(state.currentComponentData.animate.animates[index], item);
    // for(let key in item){
    //   if(state.currentComponentData.animate.animates[index]){
    //     state.currentComponentData.animate.animates[index][key] = item[key];
    //   }
    // }
    if(triggerType >= 0){
      state.currentComponentData.animate.triggerType = triggerType;
    }
  },
  addPathAnimateAttr(state, data){
    state.currentComponentData.animate['path'] = data.path;
    // Vue.set(state.currentComponentData.animate, 'path', data.path);
    state.currentComponentData.animate['gsap'] = data.gsap;
    // Vue.set(state.currentComponentData.animate, 'gsap', data.gsap);
  },
  updatePathAnimateAttr(state, data){
    _.merge(state.currentComponentData.animate, data);
  },
  updateSettingShare(state, data) {
    _.merge(state.attrs.share, data);
  },
  updateSettingMore(state, data) {
    state.attrs = _.cloneDeep(data);
  },
  updateSiteAttrs(state, attrs) {
    _.merge(state.attrs, attrs);
  },
  updateSiteStyles(state, data) {
    _.merge(state.styles, data)
  },
  updateTab(state, data) {
    for(let key in data){
      state.tabNames[key] = data[key];
    }
  },
  updateSettingBgm(state, data) {
    for(let key in state.attrs.bgm){
      state.attrs.bgm[key] = data[key]
    }
  },
  setIfTab(state, bool) {
    // 更新 底部菜单 isTab，为 true 则 禁用滑动翻页
    state.siteStatus.isTab = bool;
    if(bool){
      state.attrs.isTurnPage = false
    }
  },
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}


function isWbEventByComponentData(componentData){
  let isWb = false;
  if(componentData){
    _.forEach(componentData.events, (event) => {
      if(event.controlId && event.controlId.length > 0){
        isWb = true;
      }
    })
  }
  return isWb
}


function getPageById(id) {
  let page, i, len = state.pages.length;
  for(i = 0; i < len; i++){
    page = state.pages[i];
    if(page && page.id == id){
      return page;
    }
  }
  return state.pages[0];
}
function getPageIndexById(id) {
  let page, i, len = state.pages.length
  for(i = 0; i < len; i++){
    page = state.pages[i];
    if(page.id == id){
      return i;
    }
  }
  return -1;
}
function getComponentDataByCid(cid) {
  return ComponentTypes[cid];
}
